package com.spboot.exts.shiro;

import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.Set;

import javax.security.auth.login.AccountNotFoundException;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spboot.exts.entity.User;
import com.spboot.exts.service.UserService;

/**
 * 自定义Realm
 * 
 * @author Administrator
 *
 */
public class UserRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//根据用户id查询用户权限
		User user = (User)SecurityUtils.getSubject().getSession().getAttribute("userSession");
		Set<String> permission = userService.selectUserPermission(user.getId());
		
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(permission);
		return info;
	}

	/**
	 * 登录验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 用户账号
		String userCode = (String) token.getPrincipal();
		// 根据用户账号查询用户
		User user = userService.getOne(new QueryWrapper<User>().eq(User.USERCODE, userCode));
		if(user == null){
			//不存在
			throw new UnknownAccountException("用户不存在");
		}
		//返回用户权限信息
		return new SimpleAuthenticationInfo(user.getUserCode(),user.getUserPassword(),getName());
	}

}
